package sub2;

import java.io.Serializable;
import java.net.InetAddress;
import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.LockModeType;
import javax.persistence.ManyToMany;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Version;

/**
 * Define the entity "Peer". The registered clients are stored in the server directory (using JPA)
 * @author Magali Moulin, Pierre Labiausse
 * @version 2
 */
@NamedQueries({
	@NamedQuery(
			name = "findPeerWithInetAddressAndPort",
			query = "SELECT peer FROM Peer peer WHERE peer.inetAddress LIKE :inetAddress AND peer.port LIKE :port",
			lockMode=LockModeType.OPTIMISTIC_FORCE_INCREMENT
			),
	@NamedQuery(
			name = "listPeer",
			query = "SELECT peer FROM Peer peer",
			lockMode = LockModeType.OPTIMISTIC_FORCE_INCREMENT)
})

@Entity(name = "Peer")
@Table(name = "peer")
public class Peer implements Serializable {
	
	@Id
	@Column(name="id", nullable=false)
	@GeneratedValue (strategy=GenerationType.SEQUENCE)

	private long peerID;

	@Version
	@Column(name = "OPTLOCK")
	private int version;
	
	@Column(name = "inetAddress", nullable = false)
	private String inetAddress;
	
	@Column(name = "port", nullable= false)
	private int port;
	
	@ManyToMany(cascade = {CascadeType.PERSIST,CascadeType.MERGE },
			mappedBy = "peers")
	@JoinTable(name = "peer_fichier")
	private Set<Fichier> fichiers;
	
	/**
	 * Getter to have access to the set of shared files by a peer
	 * @return fichiers: a set of files
	 */
	public Set<Fichier> getFichiers() {
		return fichiers;
	}
	
	/**
	 * Constructor
	 */
	public Peer(){}
	
	/**
	 * Constructor of this class which take in parameters the inetAddress and the port of the peer
	 * @param inetAddress: inetAddress of the peer
	 * @param port: port of the peer
	 */
	public Peer(String inetAddress, int port){
		this.inetAddress = inetAddress;
		this.port = port;
	}
	/**
	 * Getter to have access to the port of a peer
	 * @return port
	 */
	public int getPort() {
		return port;
	}
	
	/**
	 * Add a file to the set of shared files by a peer
	 * @param fichier: name of the Fichier
	 */
	public void addFichier(Fichier fichier) {
		fichiers.add(fichier);
	}
	
	/**
	 * Getter to have access to the inetAddress of a peer
	 * @return inetAddress
	 */
	public String getInetAddress() {
		return inetAddress;
	}

	
}

